import { createRouter, createWebHistory } from 'vue-router';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';

import { appRoutes } from './routes';
import createRouteGuard from './guard';
import { getMenuName, getMenuStorage, getRouterName, getToken, isValidJSON } from '@/utils/auth';
import { DEFAULT_LAYOUT } from './routes/base';
import componentMap from './constants';

NProgress.configure({ showSpinner: false });
let menuStorage: any = getMenuStorage() || null
let allRouters: any = [...appRoutes]
if (isValidJSON(menuStorage)) {
  menuStorage = JSON.parse(menuStorage)
  const menuList: any = []
  menuStorage?.forEach((item: any) => {
    let i: any = {
      path: item?.web_url,
      name: getMenuName(item?.web_url),
      meta: {
        locale: item?.name,
        requiresAuth: true,
        order: 0,
      },
      component: DEFAULT_LAYOUT,
      children: []
    }
    item?.children?.forEach((itz: any) => {
      const componentKeyValue: any = getRouterName(itz?.web_url)
      i.children.push({
        path: itz?.web_url,
        name: getMenuName(itz?.web_url),
        meta: {
          locale: itz?.name,
          requiresAuth: true,
          order: 0,
        },
        component: () => componentKeyValue ? componentMap?.[componentKeyValue?.key]?.[componentKeyValue?.value] : null,
      })
    })
    menuList.push(i)
  })
  allRouters = [...allRouters, ...menuList]
}
const token = getToken();
const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      redirect: token ? '/home/index' : '/login',
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/login/index.vue'),
      meta: {
        requiresAuth: false,
      },
    },
    ...allRouters,
  ],
  scrollBehavior() {
    return { top: 0 };
  },
});
createRouteGuard(router);

export default router;